package com.geline.web.interceptor;

import com.geline.web.annotation.FileValidation;
import com.geline.web.util.FileValidationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 使用方式：
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
         //上传文件类型检验
         registry.addInterceptor(new FileValidationInterceptor()).addPathPatterns("/**");
     }
 * @author mengxin
 * @date 2025/3/31
 */
public class FileValidationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            FileValidation fileValidation = handlerMethod.getMethodAnnotation(FileValidation.class);
            if (fileValidation != null) {
                if (request instanceof MultipartHttpServletRequest) {
                    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                    MultipartFile file = multipartRequest.getFile("file");
                    List<MultipartFile> files = multipartRequest.getFiles("files");
                    if (file != null) {
                        if (file.isEmpty()) {
                            throw new RuntimeException("Invalid empty file");
                        }
                        FileValidationUtils.validateFile(file);
                    } else if (files != null && !files.isEmpty()) {
                        for (MultipartFile f : files) {
                            if (f.isEmpty()) {
                                throw new RuntimeException("Invalid empty file");
                            }
                            FileValidationUtils.validateFile(f);
                        }
                    } else {
                        throw new RuntimeException("No file or files attribute found in request");
                    }
                }
            }
        }
        return true;
    }
}
